import smtplib
# from CoTec.core.config.global_var import Variables
# from core.log.log_go import LogGo

from email.mime.text import MIMEText
from email.header import Header

from CoTec.utility.date.date_go import DateGo

# from core.log.log_go import LogGo

from email.mime.text import MIMEText
import smtplib
import time

import multiprocessing

class Hotmail (object):
    ready = False

    def __new__(cls, conf=None):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Hotmail, cls).__new__(cls)
            cls.config = conf
            cls.instance.init()
        return cls.instance

    def init(self):
        try:
            # Hotmail.account = conf.email_username
            # Hotmail.password = conf.email_password
            # Hotmail.config = conf

            self.account = self.config.email_username
            self.password = self.config.email_password

            self.server = smtplib.SMTP('smtp.live.com' ,port=587)
            self.server.docmd("EHLO server" )
            self.server.starttls()
            self.server.login(self.account,self.password)

            self.ready = True

            # LogGo.info('SMTP System Init Successful')
        except Exception as e:
            print(str(e))
            # LogGo.warning('SMTP System Init Failed!')

    def __send (self ,to, title, content):
        # print(self.account,self.password)
        try:
            server = smtplib.SMTP('smtp.live.com' ,port=587)
            ## server.set_debuglevel(1)
            server.docmd("EHLO server" )
            server.starttls()
            server.login(self.account,self.password)

            msg = MIMEText(content)
            msg['Content-Type' ]='text/plain; charset="utf-8"'
            msg['Subject' ] = title
            msg['From' ] = self.account
            msg['To' ] = to
            server.sendmail(self.account, to,msg.as_string())
            server.close()
        except Exception as e:
            print(str(e))

    def send_ex(self , title, content):
        # print(self.account,self.password)
        try:
            # server = smtplib.SMTP('smtp.live.com' ,port=587)
            # server.docmd("EHLO server" )
            # server.starttls()
            # server.login(self.account,self.password)
            if self.ready != True:
                return False

            mail_msg = """
            <p>""" + content + """</p>
            """

            msg = MIMEText(mail_msg, 'html', 'utf-8')
            # msg = MIMEText(content)
            msg['Content-Type' ]='text/plain; charset="utf-8"'
            msg['Subject' ] = title
            msg['From' ] = self.account
            msg['To' ] = ";".join(self.config.email_target)
            self.server.sendmail(self.account, self.config.email_target, msg.as_string())
            # server.close()

            # LogGo.info('Mail sending successful!')

            return True
        except Exception as e:
            print(str(e))

            # LogGo.warning('Mail sending failed!')
            return False

    def reports(self , content):
        try:
            if self.ready != True:
                return False

            mail_msg = """
            <p>""" + content + """</p>
            """

            title = '全球鹰计划 任务报告'

            header = ''
            header += '报告日期: ' + DateGo.get_current_date() + '\r\n'
            header += '报告内容: ' + '\r\n'
            mail_msg = header + content

            msg = MIMEText(mail_msg, 'html', 'utf-8')
            msg['Content-Type' ]='text/plain; charset="utf-8"'
            msg['Subject' ] = title
            msg['From' ] = self.account
            msg['To' ] = self.config.email_master
            self.server.sendmail(self.account, self.config.email_master, msg.as_string())

            # LogGo.info('Mail sending successful!')
            print('Mail sending successful!')
            return True
        except Exception as e:
            print(str(e))
            # LogGo.warning('Mail sending failed!')
            return False

    class QQMail(object ):
        def __init__ (self ,account,password):
            self.account="%s@qq.com" %account
            self.password=password

        def send (self ,to,title,content):
            """
            send('zsp007@Hotmail.com,zsp747@Hotmail.com")
            """
            print(self.account,self.password)
            server = smtplib.SMTP('smtp.qq.com' )
            server.set_debuglevel(1)
            ## server.docmd("EHLO server" )
            ## server.starttls()
            server.login(self.account,self.password)

            msg = MIMEText(content)
            msg['Content-Type' ]='text/plain; charset="utf-8"'
            msg['Subject' ] = title
            msg['From' ] = self.account
            msg['To' ] = to
            server.sendmail(self.account, to,msg.as_string())
            server.close()

# if __name__ == "__main__":


SMTPServerNow = None
class SMTPServer():
    cache = ''
    pool = multiprocessing.Pool(processes=3)

    # now = None
    # hotmail = Hotmail()
    @staticmethod
    def init(conf):
        Hotmail(conf)
        SMTPServer.config = conf

    @staticmethod
    def send(title, content):
        hotmail = Hotmail()
        SMTPServer.pool.apply_async(hotmail.send_ex(title, content))
        # SMTPServer.hotmail.send_ex(title, content)

    @staticmethod
    def send_error(content):
        hotmail = Hotmail()
        SMTPServer.pool.apply_async(hotmail.send_ex('Project Global Hawk < Fatal Error! >', content))
        # SMTPServer.hotmail.send_ex('Project Global Hawk < Fatal Error! >', content)

    @staticmethod
    def send_info(content):
        hotmail = Hotmail()
        SMTPServer.pool.apply_async(hotmail.send_ex('Project Global Hawk < System Information: >', content))
        # SMTPServer.hotmail.send_ex('Project Global Hawk < System Information: >', content)

    @staticmethod
    def in_report(content):
        hotmail = Hotmail()
        hotmail.reports(content)
        # SMTPServer.pool.apply_async(hotmail.report(content))

    @staticmethod
    def report(content):
        # import threading
        try:
            SMTPServer.report_task(content)
            # t = threading.Thread(target=SMTPServer.report_task(content))
            # t.setDaemon(True)
            # t.start()
            # t.join()
            return True
        except Exception as e:
            # core.log.log_go.LogGo.warning(e)
            print(repr(e))
            return False

    @staticmethod
    def report_task(content):
        try:
            SMTPServer.in_report(content)
        except Exception as e:
            # import traceback
            # msg = traceback.format_exc()
            print(repr(e))
            # LogGo.warning(msg)

        # hotmail.report(title, content)

    @staticmethod
    def fast_report(content):
        status = False

        if SMTPServer.cache != '' or SMTPServer.cache is not None:
            try:
                print('buinding reporting mail')

                if SMTPServer.report(content):
                    print('reporting mail send successful')
                    status = True
                else:
                    print('reporting mail send failed')
            except:
                print('Build email failed!')

        return status

    @staticmethod
    def build_mission_report(content):
        """积累档案"""
        SMTPServer.cache += '------ ' + DateGo.get_current_date() + '------'
        SMTPServer.cache += '\r\n'
        SMTPServer.cache += content
        SMTPServer.cache += '\r\n'

    @staticmethod
    def launch_mission_report(interval=None):
        global SMTPServerNow
        SMTPServer.cache += '\r\n'
        SMTPServer.cache += '>>>>>> ' + DateGo.get_current_date() + ' >>>>>>'

        if SMTPServerNow is None:
            SMTPServerNow = DateGo.get_current_date_raw()

        if DateGo.distance(SMTPServerNow) >= SMTPServer.config.report_interval:#Variables.report_interval:
            import socket
            hostname = 'Host name: ' + socket.gethostname()
            SMTPServer.build_mission_report(hostname)

            if SMTPServer.fast_report(SMTPServer.cache):
                SMTPServer.cache = ''
                SMTPServerNow = None

    # @staticmethod
    # def pool_to(fun):
    #     SMTPServer.pool.apply_async(fun)

# SMTPServer.report('全球鹰任务报告', '[ 严重错误:核心溶解! ]')

# print('main')

# def func(msg):
#     print("msg:", msg)s
#     time.sleep(1)
#     print("end")
#
# if __name__ == "__main__":
#     pool = multiprocessing.Pool(processes=3)
#     for i in range(4):
#         msg = "hello %d" % (i)
#         pool.apply_async(func, (msg,))  # 维持执行的进程总数为processes，当一个进程执行完毕后会添加新的进程进去
#
#     print("Mark~ Mark~ Mark~~~~~~~~~~~~~~~~~~~~~~")
#     pool.close()
#     pool.join()  # 调用join之前，先调用close函数，否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
#     print("Sub-process(es) done.")

# SMTPServer.send()
# SMTPServer.send('sayhanabi@hotmail.com',"系统日志","这是最好写点中文，如果随便写")
# SMTPServer.send_email(Variables.email_username,Variables.email_password,'sayhanabi@hotmail.com',"日志报文","系统核心严重受损")